package com.qd.controllers.hello;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

/**
 * @author taomk
 * @version 1.0
 * @since 2014/9/15 17:28
 */
@Path("")
public class HelloController {

	@Get("world")
	public String index() {
		// 返回@开始的字符串，表示将紧跟@之后的字符串显示在页面上
		return "@hello world";
	}

	@Get("json")
	public String json() {
		Gson gson = new Gson();

		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("1", "1");
		jsonMap.put("2", "2");
		jsonMap.put("3", "3");

		return "@json:"+gson.toJson(jsonMap);
//		return "@application/json:"+gson.toJson(jsonMap);
//		return "@application/x-json:"+gson.toJson(jsonMap);
	}

	@Get("xml")
	public String xml() {

		return "@xml:<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
				"<user>\n" +
				"    <id>Tao</id>\n" +
				"    <name>Mingkai</name>\n" +
				"</user>";

//		return "@application/xml:<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
//				"<user>\n" +
//				"    <id>Tao</id>\n" +
//				"    <name>Mingkai</name>\n" +
//				"</user>";
//
//		return "@application/x-xml:<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
//				"<user>\n" +
//				"    <id>Tao</id>\n" +
//				"    <name>Mingkai</name>\n" +
//				"</user>";
	}

	@Get("plain")
	public String plain() {
		return "@plain:<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
				"<user>\n" +
				"    <id>Tao</id>\n" +
				"    <name>Mingkai</name>\n" +
				"</user>";

//		return "@text:<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
//				"<user>\n" +
//				"    <id>Tao</id>\n" +
//				"    <name>Mingkai</name>\n" +
//				"</user>";

//		return "@text/plain:<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
//				"<user>\n" +
//				"    <id>Tao</id>\n" +
//				"    <name>Mingkai</name>\n" +
//				"</user>";
	}

	@Get("html")
	public String html() {
		return "@html:1<br>2<br>3";
//		return "@text/html:1<br>2<br>3";
	}

	@Get("utf8")
	public String utf8(Invocation inv) {
		Gson gson = new Gson();

		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("1", "陶");
		jsonMap.put("2", "明");
		jsonMap.put("3", "凯");

		inv.getResponse().setCharacterEncoding("UTF-8");
		return "@json:" + gson.toJson(jsonMap);
	}

	@Get("forward")
	public String forward() {
		return "f:/hello/world";
	}

	@Get("redirect")
	public String redirect() {
		return "r:/hello/world";
	}

	public String forward2() {
		// 大多数情况下，以/开始即是转发(除非存在webapp/user/test文件)
		return "/user/test";
	}

	public String nullPointerException() throws NullPointerException {
		String str = null;
		System.out.println(str.toCharArray());
		return "@hello NullPointerException";
	}

	public String runtimeException() throws RuntimeException {
		return "@hello RuntimeException";
	}

	public String error() throws Exception {
		return "@hello Exception";
	}
}
